<template>
  <!-- 大屏生产数据表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="500px"
    draggable
    @close="closeDialog"
  >
    <el-form v-show="!props.isReadonly" ref="formRef" :model="formData" :rules="rules" label-width="100">
      <el-row>
        <el-col :span="24">
          <el-form-item label="产品" prop="productId">
            <el-input
              v-model="formData.productCode"
              placeholder="请选择成品物料"
              clearable
              readonly
              style="width: 100%"
              @click="showWorkOrderSelect"
            >
              <template #append>
                <el-button type="success" plain @click="showWorkOrderSelect"
                  >选择</el-button
                >
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="生产日期" prop="productionDate">
            <el-date-picker
              v-model="formData.productionDate"
              type="date"
              placeholder="请选择生产日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="炉号" prop="equipId">
            <el-select
              v-model="formData.equipId"
              placeholder="请选择炉号"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in equipList"
                :key="`${item.id}`"
                :label="`${item.assetCode}-${item.assetName}`"
                :value="`${item.id}`"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="炉批次号" prop="furnaceBatch">
            <el-input
              v-model="formData.furnaceBatch"
              placeholder="请输入炉批次号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="熔炉状态" prop="meltedStatus">
            <el-radio-group v-model="formData.meltedStatus">
              <el-radio
                v-for="item in useDictionary('BiProductStatus')"
                :key="item.value"
                :label="Number(item.value)"
                >{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="造型状态" prop="modelingStatus">
            <el-radio-group v-model="formData.modelingStatus">
              <el-radio
                v-for="item in useDictionary('BiProductStatus')"
                :key="item.value"
                :label="Number(item.value)"
                >{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="浇注状态" prop="pouringStatus">
            <el-radio-group v-model="formData.pouringStatus">
              <el-radio
                v-for="item in useDictionary('BiProductStatus')"
                :key="item.value"
                :label="Number(item.value)"
                >{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>


    <el-descriptions
      v-show="props.isReadonly"
      title=""
      :column="1"
      size="large"
      border
      style="width: 100%"
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">顺序</div>
        </template>
        {{ formData.sort || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">炉批次号</div>
        </template>
        {{ formData.furnaceBatch || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品</div>
        </template>
        {{ formData.productName || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品图号</div>
        </template>
        {{ formData.productFigureNumber || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">生产日期</div>
        </template>
        {{ dayjs(formData.productionDate).format("YYYY-MM-DD") || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">炉号</div>
        </template>
        {{ formData.equipName || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计划状态</div>
        </template>
        {{ useDictionary("BiProductStatus", formData.planStatus) || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">熔炉状态</div>
        </template>
        {{ useDictionary("BiProductStatus", formData.meltedStatus) || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">造型状态</div>
        </template>
        {{ useDictionary("BiProductStatus", formData.modelingStatus) || "" }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">浇注状态</div>
        </template>
        {{ useDictionary("BiProductStatus", formData.pouringStatus) || "" }}
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <product-select
    :visible="productDialogSelect.visible"
    @change-visible="changeProductVisible"
    :plantId="formData.plantId"
    :materialType="3"
    :backList="productBackList"
  />
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable";
import dayjs from "dayjs"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESBIPRODUCTIONDATAADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  furnaceBatch: [
    { required: true, message: "请输入炉批次号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productId: [
    // { required: true, message: "请选择产品", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  productionDate: [
    { required: true, message: "请选择生产日期", trigger: "blur" },
  ],
  equipId: [
    // { required: true, message: "请选择炉号", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  meltedStatus: [],
  modelingStatus: [],
  pouringStatus: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  furnaceBatch: "",
  sort: "",
  productId: "",
  productName: "",
  productCode: "",
  productFigureNumber: "",
  productionDate: "",
  equipId: "",
  equipName: "",
  equipCode: "",
  planStatus: 0,
  meltedStatus: 0,
  modelingStatus: 0,
  pouringStatus: 0,
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        furnaceBatch,
        sort,
        productId,
        productName,
        productCode,
        productFigureNumber,
        productionDate,
        equipId,
        equipName,
        equipCode,
        planStatus,
        meltedStatus,
        modelingStatus,
        pouringStatus,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        furnaceBatch,
        sort,
        productId,
        productName,
        productCode,
        productFigureNumber,
        productionDate,
        equipId,
        equipName,
        equipCode,
        planStatus,
        meltedStatus,
        modelingStatus,
        pouringStatus,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.furnaceBatch = "";
  formData.sort = "";
  formData.productId = "";
  formData.productName = "";
  formData.productCode = "";
  formData.productFigureNumber = "";
  formData.productionDate = "";
  formData.equipId = "";
  formData.equipName = "";
  formData.equipCode = "";
  formData.planStatus = 0;
  formData.meltedStatus = 0;
  formData.modelingStatus = 0;
  formData.pouringStatus = 0;
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 大屏生产数据保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      const find = equipList.value.find((item) => item.id = formData.equipId);
      // debugger
      formData.equipName = find?.assetName;
      formData.equipCode = find?.assetCode;
      await request({
        url: "/mes/biproductiondata/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
//选择成品弹窗
const productDialogSelect = ref({
  visible: false,
});
const changeProductVisible = (val: boolean, data: any) => {
  productDialogSelect.value.visible = val;
  if (data) {
    formData.productId = data.id;
    formData.productName = data.materialName;
    formData.productCode = data.materialCode;
    formData.productFigureNumber = data.figureNumber;
  }
};
// 回显的数据
const productBackList = ref([]);
const showWorkOrderSelect = () => {
  productDialogSelect.value.visible = true;
};
const equipList = ref([]);
const getEquipList = () => {
  request({
    url: "/eam/eamAssetType/getList",
    method: "post",
    data: {
      assetKind: 1,
    },
  }).then(({ data }) => {
    const find = data.find((item: any) => item.assetTypeCode === "DL");
    request({
      url: "/eam/equAssetInfo/list",
      method: "post",
      data: {
        assetTypeId: find.id,
      },
    }).then((res) => {
      equipList.value = res.data;
    });
  });
};
onMounted(() => {
  getEquipList();
});
</script>
